<template>
    <div>
        <!--    面包屑导航栏-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--    卡片视图区-->
        <el-card>
            <!--            搜索与添加-->
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!--            用户列表区-->
            <el-table
                    border
                    stripe
                    :data="userList">
                <!--                索引列-->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                        align="center"
                        prop="username"
                        label="姓名">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="email"
                        label="邮箱">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="mobile"
                        label="电话">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="role_name"
                        label="角色">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                @change="userStateChange(scope.row)"
                                v-model="scope.row.mg_state">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                                   @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="removeUserById(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                                       @click="showSetRoleDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--            分页区域-->
            <el-pagination
                    class="pages"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1,2,5,10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--        添加用户对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                @close="addDialogClosed"
                width="40%">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
        </el-dialog>
        <!--        编辑用户对话框-->
        <el-dialog
                title="编辑用户信息"
                :visible.sync="editDialogVisible"
                @close="editDialogClose"
                width="50%">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
        </el-dialog>
        <!--        角色分配对话框-->
        <el-dialog
                title="角色分配"
                :visible.sync="setRoleDialogVisible"
                @close="setRoleClosed"
                width="40%">
            <p>当前用户 : {{roleInfo.username}}</p>
            <p>当前角色 : {{roleInfo.role_name}}</p>
            <p>分配角色 :
                <el-select v-model="selectedId" placeholder="请选择">
                    <el-option
                            v-for="item in roleList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                    </el-option>
                </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible= false">取 消</el-button>
    <el-button type="primary" @click="setRole">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "User",
        created() {
            this.getUserList()
        },
        data() {
            let checkEmail = (rule, value, callback) => {
                const regEmail = /^\w+@\w+(\.\w+)+$/
                if (regEmail.test(value)) {
                    // 验证成功直接返回回调函数
                    return callback()
                } else {
                    callback(new Error("请输入合法的邮箱！"))
                }
            }
            let checkPhone = (rule, value, callback) => {
                const regPhone = /^1[34578]\d{9}$/
                if (regPhone.test(value)) {
                    return callback()
                } else {
                    callback(new Error("请输入合法的手机号！"))
                }
            }
            return {
                queryInfo: {
                    // 搜索关键字
                    query: '',
                    pagenum: 1,
                    pagesize: 1
                },
                userList: [],
                total: 0,
                addDialogVisible: false,
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: '',
                },
                addFormRules: {
                    username: [
                        {required: true, message: '请输入用户名称', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号码', trigger: 'blur'},
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                },
                editDialogVisible: false,
                editForm: {},
                editFormRules: {
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入电话', trigger: 'blur'},
                        {validator: checkPhone, trigger: 'blur'}
                    ]
                },
                // 分配角色
                setRoleDialogVisible: false,
                roleInfo: {},
                roleList: [],
                selectedId: ''

            }
        },
        methods: {
            async getUserList() {
                const res = (await this.$http.get('users', {params: this.queryInfo})).data
                if (res.meta.status !== 200) {
                    return this.$message.error({
                        message: '获取用户列表失败',
                        center: true
                    })
                }
                this.userList = res.data.users
                this.total = res.data.total
                // console.log(res);
                // console.log(this.userList);
            },
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                this.getUserList()
            },
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
            async userStateChange(userInfo) {
                const res = (await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)).data
                if (res.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state
                    return this.$message.error({
                        message: "修改状态失败!",
                        center: true
                    })
                } else {
                    this.$message.success({
                        message: res.meta.msg,
                        center: true
                    })
                }
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            addUser() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    } else {
                        const res = (await this.$http.post('users', this.addForm)).data
                        if (res.meta.status != 201) {
                            return this.$message.error({
                                message: '添加用户失败',
                                center: true
                            })
                        } else {
                            this.$message.success({
                                message: '添加用户成功!',
                                center: true
                            })
                            this.addDialogVisible = false
                            this.getUserList()
                        }
                    }
                })
            },
            async showEditDialog(id) {
                const res = (await this.$http.get("users/" + id)).data
                if (res.meta.status != 200) {
                    return this.$message.error({
                        message: '查询用户信息失败!',
                        center: true
                    })
                } else {
                    this.editForm = res.data
                    this.editDialogVisible = true
                }
            },
            editDialogClose() {
                this.$refs.editFormRef.resetFields()
            },
            editUser() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return this.$message.error({
                            message: '修改用户信息失败!',
                            center: true
                        })
                    } else {
                        const res = (await this.$http.put('users/' + this.editForm.id, {
                            email: this.editForm.email,
                            mobile: this.editForm.mobile
                        })).data
                        if (res.meta.status != 200) {
                            return this.$message.error({
                                message: '更新用户信息失败!',
                                center: true
                            })
                        } else {
                            await this.getUserList()
                            this.editDialogVisible = false
                            this.$message.success({
                                message: res.meta.msg,
                                center: true
                            })
                        }
                    }
                })
            },
            async removeUserById(id) {
                const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (res == 'cancel') {
                    this.$message.info({
                        message: '取消删除!',
                        center: true
                    })
                } else {
                    const res = (await this.$http.delete('users/' + id)).data
                    if (res.meta.status !== 200) {
                        this.$message.error({
                            message: "删除用户失败!",
                            center: true
                        })
                    } else {
                        await this.getUserList()
                        this.$message.success({
                            message: "删除用户成功!",
                            center: true
                        })
                    }
                }
            },
            async showSetRoleDialog(roleInfo) {
                this.roleInfo = roleInfo
                const res = (await this.$http.get('roles')).data
                if (res.meta.status !== 200) {
                    return this.$message.error({
                        message: '获取用户角色列表失败!',
                        center: true
                    })
                } else {
                    this.setRoleDialogVisible = true
                    this.roleList = res.data

                }
            },
            async setRole() {
                if (!this.selectedId) {
                    return this.$message.error({
                        message: '请选择要分配的角色',
                        center: true
                    })
                } else {
                    const res = (await this.$http.put(`users/${this.roleInfo.id}/role`, {rid: this.selectedId})).data
                    if (res.meta.status !== 200) {
                        return this.$message.error({
                            message: '分配角色失败!',
                            center: true
                        })
                    } else {
                        this.setRoleDialogVisible = false
                        await this.getUserList()
                        this.$message.success({
                            message: '分配角色成功!',
                            center: true
                        })
                    }
                }
            },
            setRoleClosed(){
                this.selectedId = ''
            }
        }
    }
</script>

<style scoped>
    .pages {
        /*margin-left: 380px;*/
        width: 500px;
        margin: 15px auto 0 auto;
    }
</style>
